package com.leyou.order.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.auth.pojo.UserInfo;
import com.leyou.client.GoodsClient;
import com.leyou.common.pojo.PageResult;
import com.leyou.common.utils.IdWorker;
import com.leyou.order.interceptor.LoginInterceptor;
import com.leyou.order.mapper.OrderDetailMapper;
import com.leyou.order.mapper.OrderMapper;
import com.leyou.order.mapper.OrderStatusMapper;
import com.leyou.order.pojo.Order;
import com.leyou.order.pojo.OrderDetail;
import com.leyou.order.pojo.OrderStatus;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: HuYi.Zhang
 * @create: 2018-05-04 10:11
 **/
@Service
public class OrderService {
    @Autowired
    private IdWorker idWorker;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private OrderDetailMapper detailMapper;

    @Autowired
    private OrderStatusMapper statusMapper;

    private static final Logger logger = LoggerFactory.getLogger(OrderService.class);

    @Transactional
    public Long createOrder(Order order) {
        //获得登录用户信息
        UserInfo user = LoginInterceptor.getLoginUser();

        // 生成orderId
        Long orderId = idWorker.nextId();
        // 创建id
        // 获取skuid信息
        Long totalPrice111 = 0L;
        Long postFee = 0L;
        List<OrderDetail> orderDetails = order.getOrderDetails();
        for (OrderDetail sku : orderDetails) {
            Long price = sku.getPrice() * sku.getNum();
            totalPrice111 = totalPrice111 + price;
        }

        Long actualPay = 0L;
        actualPay = totalPrice111 + postFee;
        //初始化订单数据

        order.setOrderId(orderId);
        order.setUserId(user.getId());
        order.setBuyerNick(user.getUsername());
        order.setCreateTime(new Date());
        order.setBuyerRate(false);
        order.setActualPay(actualPay);
        order.setOrderDetails(orderDetails);
        order.setPostFee(postFee);
        order.setTotalPay(totalPrice111);
        this.orderMapper.insertSelective(order);

        //初始化订单状态数据
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderId(orderId);
        orderStatus.setStatus(1);// 初始状态为未付款
        orderStatus.setCreateTime(order.getCreateTime());
        this.statusMapper.insertSelective(orderStatus);

        //初始化订单详情数据
        order.getOrderDetails().forEach(detail -> detail.setOrderId(orderId));
        // 保存订单详情,使用批量插入功能
        this.detailMapper.insertList(order.getOrderDetails());

        for (OrderDetail sku : orderDetails) {
            Boolean flag = this.goodsClient.delelteStockBySkuId(sku.getSkuId(),sku.getNum());
            if (flag == false){
                throw new RuntimeException("减库存失败");
            }
        }

        // 发送rabbitMq消息
        Map<Long, List<Long>> map = new HashMap<>();
        List<Long> skuIds = orderDetails.stream().map(orderDetail -> orderDetail.getSkuId()).collect(Collectors.toList());
        map.put(user.getId(),skuIds);

        sendMqMessage(map,"cart");
        logger.debug("生成订单，订单编号：{}，用户id：{}", orderId, user.getId());
        return orderId;
    }

    public Order queryById(Long id) {
        //查询订单数据
        Order order = this.orderMapper.selectByPrimaryKey(id);

        //查询订单详情数据
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(id);
        List<OrderDetail> orderDetails = this.detailMapper.select(orderDetail);
        order.setOrderDetails(orderDetails);

        //查询订单状态
        OrderStatus orderStatus = this.statusMapper.selectByPrimaryKey(id);
        order.setStatus(orderStatus.getStatus());

        return order;
    }

    public PageResult<Order> queryUserOrderList(Integer page, Integer rows, Integer status, String key) {
        //获得登录用户信息
        UserInfo user = LoginInterceptor.getLoginUser();

        try {
            //设置分页
            PageHelper.startPage(page, rows);

            if (StringUtils.isNotBlank(key)) {
                key = "%" + key + "%";
            }

            Page<Order> pageInfo = (Page<Order>) this.orderMapper.queryOrderList(user.getId(), status, key);

            return new PageResult<>(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getResult());
        } catch (Exception e) {
            logger.error("查询订单出错", e);
            return null;
        }
    }

    @Transactional
    public Boolean updateStatus(Long id, Integer status) {
        OrderStatus record = new OrderStatus();
        record.setOrderId(id);
        record.setStatus(status);

        // 根据状态判断要修改的时间
        switch (status) {
            case 2:
                record.setPaymentTime(new Date());// 付款
                break;
            case 3:
                record.setConsignTime(new Date());// 发货
                break;
            case 4:
                record.setEndTime(new Date());// 确认收获，订单结束
                break;
            case 5:
                record.setCloseTime(new Date());// 交易失败，订单关闭
                break;
            case 6:
                record.setCommentTime(new Date());// 评价时间
                break;
            default:
                return null;
        }

        int count = this.statusMapper.updateByPrimaryKeySelective(record);
        return count == 1;
    }

    private void sendMqMessage(Map<Long,List<Long>> map, String type){
        try {
            this.amqpTemplate.convertAndSend("order."+type,map);
        } catch (AmqpException e) {
            throw  new RuntimeException("发送order ids 消息失败");
        }
    }
}
